/**
 *  This file is part of AugeasWH.
 *
 *  AugeasWH. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AugeasWH. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AugeasWH.  If not, see <http://www.gnu.org/licenses/>.
 */

package cz.fit.vutbr.pis2012.augeaswh.managers;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import cz.fit.vutbr.pis2012.augeaswh.persistence.User;

@Stateless
public class UserManager implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * Metoda vrati uzivatela ktoreho identifikuje podla uzivatelskeho mena. 
	 * Pokial uzivatel neexistuje vrati null object
	 * @param name uzivatelske meno
	 * @return objekt uzivatela
	 */
	public User getUserByName(String name)
	{
		@SuppressWarnings("unchecked")
		List<User> list = em.createQuery("SELECT u FROM User u WHERE u.name = :name")
								.setParameter("name", name).getResultList();
		return list.size() > 0 ? list.get(0) : null;
	}
	
	/**
	 * Metoda vrati uzivatela ktoreho identifikuje podla uzivatelskeho mena a hesla. Heslo je ulozene v plain texte
	 * Pokial uzivatel neexistuje vrati null object 
	 * @param name uzivatelske meno
	 * @param password uzivatelske heslo
	 * @return objekt uzivatela
	 */
	public User getUserByNameAndPassword(String name, String password) {
		@SuppressWarnings("unchecked")
		List<User> list = em.createQuery("SELECT u FROM User u WHERE u.name = :name AND u.password = :password")
								.setParameter("name", name).setParameter("password", password).getResultList();		
		return list.size() > 0 ? list.get(0) : null;
	}
	
	/**
	 * Vrati zoznam vsetkych uzivatelov v databaze
	 * @return Zoznam vsetkych uzivatelov
	 */
	public List<User> getAllUsers() {
		@SuppressWarnings("unchecked")
		List<User> lst = em.createQuery("SELECT u FROM User u").getResultList();
		return lst;
	}
	
	/**
	 * Vymaze z databazy dany zaznam
	 * @param user zaznam 
	 */
	public void deleteUser(User user) {
	    em.remove(em.merge(user));
	}
	
	public void saveOrUpdateUser(User user) {
		em.merge(user);
	}
	
}
